// components/qrcode/index.js
import drawQrcode from '../../utils/qrcode.js'
Component({
  options: {
    addGlobalClass: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    canvasid: {
      type: String,
      value: 'myQrcode'
    },
    text: {
      type: String,
      value: 'myQrcode'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    visible: false,
    codePath: ''
  },
  ready() {
    this.drawcode()
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 绘制二维码
    drawcode() {
      let that = this
      const query = this.createSelectorQuery()
      query.select('#' + that.data.canvasid)
        .fields({
          node: true,
          size: true
        })
        .exec((res) => {
          console.log(res)
          var canvas = res[0].node

          // 调用方法drawQrcode生成二维码
          drawQrcode({
            canvas: canvas,
            canvasId: 'myQrcode',
            width: 260,
            padding: 30,
            background: '#ffffff',
            foreground: '#000000',
            text: that.data.text,
          })
          console.log(that.data.text)
          // 获取临时路径（得到之后，想干嘛就干嘛了）
          wx.canvasToTempFilePath({
            canvasId: 'myQrcode',
            canvas: canvas,
            x: 0,
            y: 0,
            width: 260,
            height: 260,
            destWidth: 260,
            destHeight: 260,
            success(res) {
              console.log('二维码临时路径：', res.tempFilePath)
              that.setData({
                codePath: [res.tempFilePath]
              })
            },
            fail(res) {
              console.error(res)
            }
          })
        })
    },
    // 展示二维码
    showCode() {
      this.setData({
        visible: !this.data.visible
      })
    }
  }
})